#Requires AutoHotkey v2.0
; #include private\private_hotkey.ahk
; 只获取目录:
SplitPath A_LineFile,, &file_dir
SetWorkingDir file_dir

; 加载配置文件
load_cfg(cfg_file:="cfg.ini"){
    for key in ["folder", "app_caller"] {
        try {
            section := IniRead(cfg_file, key)
        }
        catch {
            continue
        }
        for index, line in StrSplit(section, "`n") {
            if (SubStr(line, 1, 1) = "#"){ ; 跳过注释行
                continue
            }
            pair := StrSplit(line, "=")
            proc := pair[1]
            path := pair[2]
            SplitPath(path, &name)
            if (key = "app_caller"){ ; 可能需要特殊处理的
                if (proc = "vscode"){
                    exe := "Code.exe"
                }
                else if(proc = "term"){
                    exe := "WindowsTerminal.exe"
                }
                else{
                    exe := name
                }
                CfgMap[key][proc] := [path, exe]
            }
            else{
                CfgMap[key][proc] := path
            }
            ; MsgBox Format("{}, {}, {}, {}", key, proc, path, exe)
        }
    }
}

; 初始化
init(){
    ; 设置python环境变量
    EnvSet("PYTHONPATH", A_WorkingDir "\common")

    global CfgMap := Map()
    local_path := EnvGet("LOCALAPPDATA")
    CfgMap["folder"] := Map()
    CfgMap["folder"]["home"]      := local_path
    CfgMap["folder"]["downloads"] := "D:\Users\qiang.cao\Downloads"
    CfgMap["folder"]["shortcuts"] := "D:\Users\qiang.cao\My Documents\My Pictures"
    CfgMap["folder"]["folder"]    := "explorer.exe"

    CfgMap["app_caller"] := Map()
    CfgMap["app_caller"]["vscode"]       := ["code", "Code.exe"]
    CfgMap["app_caller"]["wxwork"]       := ["C:\Program Files (x86)\WXWork\WXWork.exe", "WXWork.exe"]
    CfgMap["app_caller"]["dict"]         := [local_path "\youdao\dict\Application\YoudaoDict.exe", "YoudaoDict.exe"]
    CfgMap["app_caller"]["word"]         := ["C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE", "WINWORD.EXE",]
    CfgMap["app_caller"]["ppt"]          := ["C:\Program Files (x86)\Microsoft Office\root\Office16\POWERPNT.EXE", "POWERPNT.EXE"]
    CfgMap["app_caller"]["excel"]        := ["C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE", "EXCEL.EXE"]
    CfgMap["app_caller"]["term"]         := [local_path "\Microsoft\WindowsApps\wt.exe", "WindowsTerminal.exe"]
    CfgMap["app_caller"]["pycharm"]      := ["C:\Program Files\JetBrains\PyCharm Community Edition 2024.1.7\bin\pycharm64.exe", "pycharm64.exe"]
    CfgMap["app_caller"]["edge"]         := ["C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", "msedge.exe"]
    CfgMap["app_caller"]["chrome"]       := ["C:\Program Files\Google\Chrome\Application\chrome.exe", "chrome.exe"]
    CfgMap["app_caller"]["klayout"]      := ["C:\Program Files (x86)\KLayout\klayout_app.exe", "klayout_app.exe"]
    CfgMap["app_caller"]["klayout_0.28"] := ["C:\Program Files (x86)\KLayout_0.28\klayout_app.exe", "klayout_app.exe"]

    ; 加载外部配置文件
    load_cfg()
}

; 获取当前选中字符串
get_select_text(mode:=0){
    ; mode: 0, 会修改剪贴板, 1, 不会修改剪贴板
    if mode == 1 {
        ; 保存剪贴板已有的内容
        clipboard_saved := A_Clipboard
    }
    ; 清空剪贴板内容
    A_Clipboard := ""
    Send("^c")
    ClipWait(0.1)
    select_text := A_Clipboard
    if mode == 1 {
        ; 恢复之前的内容到剪贴板
        A_Clipboard := clipboard_saved
    }
    ; if select_text != "" {
    ;     ; 根据结尾字符是否是回车来判断是否是由于 ctrl+c复制整行造成的
    ;     ; 因为有的编辑器在不选中文字的情况下, 使用ctrl+c会复制一整行
    ;     ; 这个判断方式在obsidian上无效, 即使obsidian复制了一整行, 最后一个字符也也不是换行符
    ;     select_text_endchar := SubStr(select_text, -1, 1)
    ;     if (select_text_endchar = "`n") { ; 没有选中文字
    ;         select_text := ""
    ;     }
    ; }
    return select_text
}

; 在字符串外面加包围字符
arround_text(char){
    str_src := get_select_text()
    if str_src != "" { ; 选中内容需要做操作
        r := Format("({}).+({})", char, char)
        found_pos := RegExMatch(str_src, r, &sub_pat)
        if found_pos == 0 { ; 如果未被char包围则添加char
            str_dst := char str_src char
        }
        else if sub_pat.Count == 2 { ; 如果被char包围则删掉char
            s1 := SubStr(str_src, 1, sub_pat.Pos[1] - 1)
            s2 := SubStr(str_src, sub_pat.Pos[1] + 1, sub_pat.Pos[2] - sub_pat.Pos[1] - 1)
            s3 := SubStr(str_src, sub_pat.Pos[2] + 1)
            str_dst :=  s1 s2 s3
        }
        A_Clipboard := str_dst
        Send "^v"
    }
}

; 字符char重复count次
repeat_char(char, count){
    text := ""
    Loop count {
        text .= char
    }
    return text
}

; 拼接分割线, 用剪贴板更流畅
split_line(prefix, char, count){
    ; clipboard_saved := A_Clipboard
    A_Clipboard := prefix repeat_char(char, count) "`n"
    ; ClipWait(0.1)
    Send "^v"
    ; A_Clipboard := clipboard_saved
}

; 找出进程并切换到此进程
activate_process(proc){
    if CfgMap["app_caller"].Has(proc){
        path := CfgMap["app_caller"][proc][1]
        exe := CfgMap["app_caller"][proc][2]
    }
    else{
        path := proc
        exe := proc
    }
    if not WinExist("ahk_exe" exe){
        Run path
        if WinWaitActive("ahk_exe" exe, , 2){
            ; MsgBox "找到了" proc
            WinShow
            WinActivate
        }
    }
    else{
        WinShow
        WinActivate
    }
}

; 通过剪切板输出字符串
sendby_clipboard(text){
    A_Clipboard := text
    ClipWait(0.1)
    Send "^v"
}

; # :win 键
; ! :alt
; ^ :ctrl
; + :shift

; # !keyboard maestro! 热键
; ctrl+a            1不显示企微chat
; none              2存储微信照片视频
; ctrl+alt+cmd+9    3stop all macros

; #keyboard
; shift+cmd+w       home            防止"关闭所有"误操作        enabled

init()

; cmd+.             home            "选中东西"的右键菜单        enabled
#.::{
    if get_select_text() != ""
        Send "{Click Right}"
}

; cmd+\             home            "鼠标位置"的右键菜单        enabled
#\::Send "{Click Right}"

; 打开windows应用搜索
#f::Send "^{Escape}" ; {ctrl}+{esc}

; ------------
; alt+9             处理text        对齐table (py脚本)          enabled
!9::{
    Send "^c"
    ClipWait(0.1)
    RunWait("python common\action.py arrange_table", A_WorkingDir, "Hide")
    ; RunWait(A_ComSpec Format(' /k python "{}\common\action.py" arrange_table', A_WorkingDir), A_WorkingDir)
    Send "^v"
}
; alt+0             处理text        format article (py脚本)     enabled
!0::{
    RunWait("python common\action.py format", A_WorkingDir, "Hide")
    ; RunWait(A_ComSpec Format(' /k python "{}\common\action.py" format', A_WorkingDir), A_WorkingDir)
    Send "^v"
}

; alt+z             处理text        在两边加上双引号            enabled
!z::arround_text('"')

; alt+\             处理text        在两边加上叹号              enabled    不常用, 我都忘了
!\::arround_text('`!')

; alt+;             处理text        在两边加上"⠇"               enabled
!;::arround_text('⠇')

; ctrl+alt+c        保存网页和网址  把"当前网页url"放到pycharm  enabled
^!c::{
    ; activate_process("edge")
    Send "!d"
    Send "^c"
    ClipWait(0.5)
    activate_process("pycharm")
    A_Clipboard := "# " A_Clipboard "`n"
    Send "^v"
}

; #key sequence
; sjjj              home            当前时间                    enabled
:*:sjjj::{
    ; note 修改直接Send为通过剪切版, 一次性输出出来, 减少付彪出问题概率
    ; Send FormatTime(, "yyyy-MM-dd HH-mm-ss ") FormatTime(, "(ddd)")
    sendby_clipboard(FormatTime(, "yyyy-MM-dd HH-mm-ss ") FormatTime(, "(ddd)"))
}
:*:rq::  {
    sendby_clipboard(FormatTime(, "yyyy/MM/dd"))
}
; nntt              home            notice:                     enabled
:*:nntt::{
    sendby_clipboard("notice:")
}
; xjjj              home            详见小节""                  enabled
:*:xjjj::{
    sendby_clipboard('详见小节""')
}
; cmmm              home            "#wj注释: "                 enabled
:*:cmmm::{
    sendby_clipboard("⠇我自己注释⠇:")
}
; dfff              home            todo???                     enabled
:*:dfff::{
    sendby_clipboard("todo???")
}
; pccc              home            "#pic--> "                  enabled
:*:pccc::{
    sendby_clipboard("#pic--> ")
}

; ------------
; ctrl+0            输入text        " --> "                     enabled
^0::Send sendby_clipboard(" --> ")
; ctrl+7            输入text        "🔺"                        enabled
^7::Send sendby_clipboard("🔺")
; ctrl+6            输入text        "🌟"                        enabled
^6::Send sendby_clipboard("🌟")
; alt+1             输入text        "# " + "-"*132              enabled
!1::Send split_line("# ", "-", 132)
; alt+2             输入text        "# " + "~"* 80              enabled
!2::Send split_line("# ", "~", 80)
; alt+3             输入text        "# " + "."* 32              enabled
!3::Send split_line("# ", ".", 32)
; alt+4             输入text        "-"* 12                     enabled
!4::Send split_line("", "-", 12)
; ctrl+9            输入text        一个tab                     enabled
^9::Send sendby_clipboard("`t")

; ------------
; alt+a             screen shot     截屏并放入ppt               enabled
!a::{
    Send "{PrintScreen}"
    activate_process("ppt")
    ; SetWinDelay 100 ; ms
    Send "^m"
    ClipWait(0.1)
    Send "^v"
}
; ------------
; ctrl+alt+f        打开文件夹      打开finder并显示"family"    enabled    不常用, 我都忘了
^!f::Run CfgMap["folder"]["home"]
; ctrl+alt+l        打开文件夹      打开finder并显示"downloads" enabled    不常用, 我都忘了
^!l::Run CfgMap["folder"]["downloads"]
; ctrl+alt+s        打开文件夹      打开finder并显示"shortcuts" enabled    不常用, 我都忘了
^!s::Run CfgMap["folder"]["shortcuts"]
; ctrl+alt+m        打开文件夹      打开finder并显示"macfolder" enabled    不常用, 我都忘了
^!m::Run CfgMap["folder"]["folder"]
; ------------
; shift+alt+1       window size     最大化window                enabled
; +!1::WinMaximize "A" ; note 与pycharm快捷键冲突, 建议直接按{win}+{up}
; shift+alt+2       window size     把window铺在左边            enabled
; +!2::Send "#{Left}"  ; note 有冲突暂时无法解决, 建议直接按{win}+{left}
; shift+alt+3       window size     把window铺在右边            enabled
; +!3::Send "#{Right}" ; note 有冲突暂时无法解决, 建议直接按{win}+{right}
; ------------
; alt+b             app caller      vscode                      enabled
!b::activate_process("vscode")
; alt+c             app caller      safari                      ?好像没用
!c::activate_process("edge")
; alt+e             app caller      企微                        enabled
!e::activate_process("wxwork")
; alt+f             app caller      finder                      enabled
!f::Send "#e"
; alt+g             app caller      有道词典                    enabled
!g::activate_process("dict")
; alt+h             app caller      ms word                     enabled
!h::activate_process("word")
; fn+cmd+j          app caller      klayout                     enabled
#j::activate_process("klayout")
; alt+k             app caller      klayout v0.28.12            enabled
!k::activate_process("klayout_0.28")
; ctrl+cmd+m        app caller      activity monitor            enabled  # 2024-10-18 09-08-31 (Fri)
^#m::Send "^+{Escape}" ; {ctrl}+{shift}+{esc}
; alt+p             app caller      ppt                         enabled
!p::activate_process("ppt")
; alt+r             app caller      excel                       enabled
!r::activate_process("excel")
; alt+t             app caller      iterm                       enabled
!t::activate_process("term")
; alt+u             app caller      pycharm ce                  enabled
!u::activate_process("pycharm")
; alt+x             app caller      chrome                      enabled
!x::activate_process("chrome")

